<template>
  <div class="role-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchRoles">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="primary" :icon="Plus" @click="openAddDialog">新增角色</el-button>
      <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="selectedRoles.length === 0">
        批量删除
      </el-button>
    </el-card>

    <!-- 角色列表 -->
    <el-card>
      <el-table
        :data="roleList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="角色ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="warning" :icon="Key" size="small" @click="openPermissionDialog(row)">权限</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deleteRole(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveRole" :loading="saveLoading">
          {{ dialogType === 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="角色权限配置"
      width="600px"
      @close="closePermissionDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="currentRole.name" readonly />
        </el-form-item>
        <el-form-item label="权限列表">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTreeData"
            show-checkbox
            node-key="id"
            :default-checked-keys="selectedPermissions"
            :props="{ label: 'name', children: 'children' }"
            style="max-height: 400px; overflow-y: auto"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closePermissionDialog">取消</el-button>
        <el-button type="primary" @click="saveRolePermissions" :loading="permissionLoading">
          保存权限
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, Key } from '@element-plus/icons-vue'
import { 
  getRolePage, 
  getRoleById, 
  saveOrUpdateRole, 
  deleteRoles, 
  getPermissionList, 
  getPermissionsByRoleId,
  setRolePermissions 
} from '@/api/system'

// 搜索表单
const searchForm = ref({
  name: '',
  code: '',
  status: ''
})

// 角色列表数据
const roleList = ref([])
const loading = ref(false)
const selectedRoles = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框参数
const dialogVisible = ref(false)
const dialogType = ref('add')
const saveLoading = ref(false)

// 权限配置对话框
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const currentRole = ref({})
const permissionTreeData = ref([])
const selectedPermissions = ref([])
const permissionTreeRef = ref()

// 表单数据
const form = ref({
  id: '',
  name: '',
  code: '',
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z_]+$/, message: '只能包含字母和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

const formRef = ref()

// 加载角色列表
const loadRoleList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }
    const res = await getRolePage(params)
    roleList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error('Failed to load role list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索角色
const searchRoles = () => {
  currentPage.value = 1
  loadRoleList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    code: '',
    status: ''
  }
  currentPage.value = 1
  loadRoleList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRoles.value = val
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadRoleList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadRoleList()
}

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    await saveOrUpdateRole({
      ...row,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    name: '',
    code: '',
    description: '',
    sort: 0,
    status: 1
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    const res = await getRoleById(row.id)
    form.value = { ...res }
    dialogType.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取角色详情失败')
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 保存角色
const saveRole = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    
    await saveOrUpdateRole(form.value)
    ElMessage.success(dialogType.value === 'add' ? '新增角色成功' : '更新角色成功')
    closeDialog()
    loadRoleList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(dialogType.value === 'add' ? '新增角色失败' : '更新角色失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 删除角色
const deleteRole = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteRoles([row.id])
    ElMessage.success('删除角色成功')
    loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除角色失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要删除的角色')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRoles.value.map(item => item.id)
    await deleteRoles(ids)
    ElMessage.success('批量删除角色成功')
    loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除角色失败')
    }
  }
}

// 打开权限配置对话框
const openPermissionDialog = async (row) => {
  currentRole.value = row
  permissionDialogVisible.value = true
  
  try {
    // 加载权限树
    const permissions = await getPermissionList()
    permissionTreeData.value = buildPermissionTree(permissions)
    
    // 加载角色已有的权限
    const rolePermissions = await getPermissionsByRoleId(row.id)
    selectedPermissions.value = rolePermissions.map(p => p.id)
    
    nextTick(() => {
      permissionTreeRef.value?.setCheckedKeys(selectedPermissions.value)
    })
  } catch (error) {
    ElMessage.error('加载权限数据失败')
  }
}

// 构建权限树
const buildPermissionTree = (permissions) => {
  const tree = []
  const map = {}
  
  // 创建映射
  permissions.forEach(permission => {
    map[permission.id] = { ...permission, children: [] }
  })
  
  // 构建树结构
  permissions.forEach(permission => {
    if (permission.parentId === '0' || !permission.parentId) {
      tree.push(map[permission.id])
    } else if (map[permission.parentId]) {
      map[permission.parentId].children.push(map[permission.id])
    }
  })
  
  return tree
}

// 关闭权限配置对话框
const closePermissionDialog = () => {
  permissionDialogVisible.value = false
  currentRole.value = {}
  selectedPermissions.value = []
  permissionTreeData.value = []
}

// 保存角色权限
const saveRolePermissions = async () => {
  try {
    permissionLoading.value = true
    const permissionIds = permissionTreeRef.value?.getCheckedKeys() || []
    
    await setRolePermissions(currentRole.value.id, permissionIds)
    ElMessage.success('权限配置成功')
    closePermissionDialog()
  } catch (error) {
    ElMessage.error('权限配置失败')
  } finally {
    permissionLoading.value = false
  }
}

// 初始化加载
onMounted(() => {
  loadRoleList()
})
</script>

<style scoped>
.role-list {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
}
</style>